from _decimal import Decimal
from django_redis import get_redis_connection
from rest_framework import serializers
from .models import OrderGoods
from goods.models import SKU
from django.utils import timezone


class CartSKUSerializer(serializers.ModelSerializer):
    """
    购物车商品数据序列化器
    """
    count = serializers.IntegerField(label='数量')

    class Meta:
        model = SKU
        fields = ('id', 'name', 'default_image_url', 'price', 'count')

class PlaceOrderSerialzier(serializers.Serializer):
    """
        订单结算数据序列化器
        """
    freight = serializers.DecimalField(label='运费', max_digits=10, decimal_places=2)
    skus = CartSKUSerializer(many=True)


from order.models import OrderInfo
class OrderCommitSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderInfo
        fields = ('order_id', 'address', 'pay_method')
        read_only_fields = ('order_id',)
        extra_kwargs = {
            'address': {
                'write_only': True,
                'required': True,
            },
            'pay_method': {
                'write_only': True,
                'required': True
            }
        }


    def create(self, validated_data):
        """
        # 1. 获取address,pay_method,user
        # 2. 生成一个orde_id
        # 3. 初始化总个数,总价格,总运费信息
        # 4. 状态信息
        # 5. 订单信息生成
        # 6. 订单信息生成之后,可以记录商品订单信息(1:n,先有订单)
        # 7. 获取redis数据,
        # 8. 进行遍历,将数据 保存到 商品订单中
        # 9. 修改商品的库存和销量
        # 10. 对商品个数和商品价格进行统计
        # 11. 删除redis的数据
        """
        # 1. 获取address,pay_method,user
        user = self.context['request'].user
        address = validated_data.get('address')
        pay_method = validated_data.get('pay_method')
        # 2. 生成一个orde_id
        # Y year m month  d  day  H hour M minute S second
        order_id = timezone.now().strftime("%Y%m%d%H%M%S%f") + ('%09d'%user.id)
        # 3. 初始化总个数,总价格,总运费信息
        total_count = 0
        total_amount = Decimal('0')
        freight = Decimal('10.00')
        # 4. 状态信息
        if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:
            # 货到付款
            status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        else:
            # 支付
            status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']


        # 5. 订单信息生成
        order = OrderInfo.objects.create(
            order_id = order_id,
            user = user,
            address = address,
            total_amount = total_amount,
            total_count = total_count,
            freight = freight,
            pay_method = pay_method,
            status = status
        )
        # 6. 订单信息生成之后,可以记录商品订单信息(1:n,先有订单)

        # 7. 获取redis数据,
        redis_conn = get_redis_connection('cart')

        redis_cart = redis_conn.hgetall("cart_%s"%user.id)
        redis_selected_ids = redis_conn.smembers('cart_selected_%s' % user.id)
        # 8. 进行遍历,将数据 保存到 商品订单中
        cart = {}

        for sku_id in redis_selected_ids:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        ids = cart.keys()

        for sku_id in ids:
            sku = SKU.objects.get(pk=sku_id)

            # 获取商品购买的数据
            count = cart[sku_id]

            # 判断库存和购买量
            if sku.stock < count:
                raise serializers.ValidationError('库存不足谢谢')

            # 9. 修改商品的库存和销量
            sku.stock -= count
            sku.sales += count
            sku.save()

            # 入库
            OrderGoods.objects.create(
                order=order,
                sku=sku,
                count=count,
                price=sku.price
            )



            # 10. 对商品个数和商品价格进行统计
            order.total_count += count
            order.total_amount += (count*sku.price)


        order.save()

        # 11. 删除redis的数据
        


        return validated_data


    pass






















